package com.cmq.web_1.api_test;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@WebServlet("/api/students")
public class StudentApiServlet extends HttpServlet {
    private StudentService studentService;

    @Override
    public void init() throws ServletException {
        studentService = new StudentService();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置响应类型和编码
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();
        Map<String, String> params = getRequestParameters(request);

        try {
            String action = params.getOrDefault("action", "search");

            switch (action) {
                case "getAll":
                    handleGetAllStudents(response, out);
                    break;
                case "getById":
                    handleGetStudentById(params, response, out);
                    break;
                case "getByName":
                    handleGetStudentsByName(params, response, out);
                    break;
                case "getByClass":
                    handleGetStudentsByClass(params, response, out);
                    break;
                case "getByMajor":
                    handleGetStudentsByMajor(params, response, out);
                    break;
                case "getByGender":
                    handleGetStudentsByGender(params, response, out);
                    break;
                case "search":
                    handleSearchStudents(params, response, out);
                    break;
                case "getClasses":
                    handleGetAllClasses(response, out);
                    break;
                case "getMajors":
                    handleGetAllMajors(response, out);
                    break;
                case "getCount":
                    handleGetStudentCount(response, out);
                    break;
                default:
                    sendErrorResponse(response, out, 400, "不支持的action参数: " + action);
                    break;
            }

        } catch (Exception e) {
            sendErrorResponse(response, out, 500, "服务器内部错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 获取所有学生
    private void handleGetAllStudents(HttpServletResponse response, PrintWriter out) {
        List<Student> students = studentService.getAllStudents();
        ApiResponse<List<Student>> apiResponse = ApiResponse.success("获取所有学生成功", students);
        out.print(JsonUtil.toJson(apiResponse));
    }

    // 根据学号查询学生
    private void handleGetStudentById(Map<String, String> params, HttpServletResponse response, PrintWriter out) {
        String id = params.get("id");
        if (id == null || id.trim().isEmpty()) {
            sendErrorResponse(response, out, 400, "学号参数不能为空");
            return;
        }

        Student student = studentService.getStudentById(id);
        if (student != null) {
            ApiResponse<Student> apiResponse = ApiResponse.success("查询学生成功", student);
            out.print(JsonUtil.toJson(apiResponse));
        } else {
            sendErrorResponse(response, out, 404, "学生不存在: " + id);
        }
    }

    // 根据姓名查询学生
    private void handleGetStudentsByName(Map<String, String> params, HttpServletResponse response, PrintWriter out) {
        String name = params.get("name");
        if (name == null || name.trim().isEmpty()) {
            sendErrorResponse(response, out, 400, "姓名参数不能为空");
            return;
        }

        List<Student> students = studentService.getStudentsByName(name);
        ApiResponse<List<Student>> apiResponse = ApiResponse.success("按姓名查询成功", students);
        out.print(JsonUtil.toJson(apiResponse));
    }

    // 根据班级查询学生
    private void handleGetStudentsByClass(Map<String, String> params, HttpServletResponse response, PrintWriter out) {
        String className = params.get("className");
        if (className == null || className.trim().isEmpty()) {
            sendErrorResponse(response, out, 400, "班级参数不能为空");
            return;
        }

        List<Student> students = studentService.getStudentsByClass(className);
        ApiResponse<List<Student>> apiResponse = ApiResponse.success("按班级查询成功", students);
        out.print(JsonUtil.toJson(apiResponse));
    }

    // 根据专业查询学生
    private void handleGetStudentsByMajor(Map<String, String> params, HttpServletResponse response, PrintWriter out) {
        String major = params.get("major");
        if (major == null || major.trim().isEmpty()) {
            sendErrorResponse(response, out, 400, "专业参数不能为空");
            return;
        }

        List<Student> students = studentService.getStudentsByMajor(major);
        ApiResponse<List<Student>> apiResponse = ApiResponse.success("按专业查询成功", students);
        out.print(JsonUtil.toJson(apiResponse));
    }

    // 根据性别查询学生
    private void handleGetStudentsByGender(Map<String, String> params, HttpServletResponse response, PrintWriter out) {
        String gender = params.get("gender");
        if (gender == null || gender.trim().isEmpty()) {
            sendErrorResponse(response, out, 400, "性别参数不能为空");
            return;
        }

        if (!gender.equals("男") && !gender.equals("女")) {
            sendErrorResponse(response, out, 400, "性别参数必须是'男'或'女'");
            return;
        }

        List<Student> students = studentService.getStudentsByGender(gender);
        ApiResponse<List<Student>> apiResponse = ApiResponse.success("按性别查询成功", students);
        out.print(JsonUtil.toJson(apiResponse));
    }

    // 多条件组合查询
    private void handleSearchStudents(Map<String, String> params, HttpServletResponse response, PrintWriter out) {
        List<Student> students = studentService.searchStudents(params);
        String message = "搜索完成，找到 " + students.size() + " 个学生";
        ApiResponse<List<Student>> apiResponse = ApiResponse.success(message, students);
        out.print(JsonUtil.toJson(apiResponse));
    }

    // 获取所有班级列表
    private void handleGetAllClasses(HttpServletResponse response, PrintWriter out) {
        List<String> classes = studentService.getAllClasses();
        ApiResponse<List<String>> apiResponse = ApiResponse.success("获取班级列表成功", classes);
        out.print(JsonUtil.toJson(apiResponse));
    }

    // 获取所有专业列表
    private void handleGetAllMajors(HttpServletResponse response, PrintWriter out) {
        List<String> majors = studentService.getAllMajors();
        ApiResponse<List<String>> apiResponse = ApiResponse.success("获取专业列表成功", majors);
        out.print(JsonUtil.toJson(apiResponse));
    }

    // 获取学生总数
    private void handleGetStudentCount(HttpServletResponse response, PrintWriter out) {
        int count = studentService.getStudentCount();
        ApiResponse<Integer> apiResponse = ApiResponse.success("获取学生总数成功", count);
        out.print(JsonUtil.toJson(apiResponse));
    }

    // 获取请求参数
    private Map<String, String> getRequestParameters(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Enumeration<String> paramNames = request.getParameterNames();

        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            params.put(paramName, request.getParameter(paramName));
        }

        return params;
    }

    // 发送错误响应
    private void sendErrorResponse(HttpServletResponse response, PrintWriter out,
                                   int statusCode, String message) {
        response.setStatus(statusCode);
        ApiResponse<Object> apiResponse = ApiResponse.error(message, statusCode);
        out.print(JsonUtil.toJson(apiResponse));
    }
}